package com.ryder.petmatediarybackend.module.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ryder.petmatediarybackend.common.exception.BusinessException;
import com.ryder.petmatediarybackend.module.shop.dto.CreateQualificationDTO;
import com.ryder.petmatediarybackend.module.shop.entity.ShopInfo;
import com.ryder.petmatediarybackend.module.shop.entity.ShopQualification;
import com.ryder.petmatediarybackend.module.shop.mapper.ShopQualificationMapper;
import com.ryder.petmatediarybackend.module.shop.service.ShopInfoService;
import com.ryder.petmatediarybackend.module.shop.service.ShopQualificationService;
import com.ryder.petmatediarybackend.module.shop.vo.QualificationVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述: 店铺资质表（含疫苗资质）(ShopQualification)表服务实现类
 * 
 * @author Ryder
 * @version 1.0
 * @since 1.0
 * 更新日期: 2025-10-31
 */
@Slf4j
@Service("shopQualificationService")
@RequiredArgsConstructor
public class ShopQualificationServiceImpl extends ServiceImpl<ShopQualificationMapper, ShopQualification> implements ShopQualificationService {

    private final ShopInfoService shopInfoService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QualificationVO createQualification(Long userId, CreateQualificationDTO dto) {
        log.info("[创建资质] userId={}, qualificationName={}", userId, dto.getQualificationName());

        // 检查店铺是否存在
        ShopInfo shopInfo = shopInfoService.getShopByUserId(userId);
        if (shopInfo == null) {
            throw new BusinessException("请先创建店铺");
        }

        // 创建资质
        ShopQualification qualification = new ShopQualification();
        BeanUtil.copyProperties(dto, qualification);
        qualification.setShopId(shopInfo.getId());
        
        // 设置图片JSON字段
        if (dto.getQualificationImages() != null && !dto.getQualificationImages().isEmpty()) {
            qualification.setQualificationImages(JSONUtil.toJsonStr(dto.getQualificationImages()));
        }

        // 设置默认状态
        qualification.setAuditStatus(0); // 待审核

        boolean saved = this.save(qualification);
        if (!saved) {
            throw new BusinessException("创建资质失败");
        }

        log.info("[创建资质成功] qualificationId={}", qualification.getId());
        return convertToVO(qualification);
    }

    @Override
    public List<QualificationVO> getMyQualifications(Long userId) {
        ShopInfo shopInfo = shopInfoService.getShopByUserId(userId);
        if (shopInfo == null) {
            throw new BusinessException("店铺不存在");
        }

        LambdaQueryWrapper<ShopQualification> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShopQualification::getShopId, shopInfo.getId())
                .orderByDesc(ShopQualification::getCreateTime);
        
        List<ShopQualification> list = this.list(wrapper);
        return list.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteQualification(Long userId, Long qualificationId) {
        log.info("[删除资质] userId={}, qualificationId={}", userId, qualificationId);

        ShopInfo shopInfo = shopInfoService.getShopByUserId(userId);
        if (shopInfo == null) {
            throw new BusinessException("店铺不存在");
        }

        ShopQualification qualification = this.getById(qualificationId);
        if (qualification == null) {
            throw new BusinessException("资质不存在");
        }

        if (!qualification.getShopId().equals(shopInfo.getId())) {
            throw new BusinessException("无权删除该资质");
        }

        boolean deleted = this.removeById(qualificationId);
        if (!deleted) {
            throw new BusinessException("删除资质失败");
        }

        log.info("[删除资质成功] qualificationId={}", qualificationId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void applyVaccinePermission(Long userId) {
        log.info("[申请疫苗资质] userId={}", userId);

        ShopInfo shopInfo = shopInfoService.getShopByUserId(userId);
        if (shopInfo == null) {
            throw new BusinessException("店铺不存在");
        }

        // 检查是否有动物诊疗许可证且已审核通过
        LambdaQueryWrapper<ShopQualification> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShopQualification::getShopId, shopInfo.getId())
                .eq(ShopQualification::getQualificationType, 2) // 动物诊疗许可证
                .eq(ShopQualification::getAuditStatus, 1); // 审核通过
        
        long count = this.count(wrapper);
        if (count == 0) {
            throw new BusinessException("请先提交动物诊疗许可证并通过审核");
        }

        // 更新店铺疫苗权限（实际应该提交审核，这里简化处理）
        shopInfo.setHasVaccinePermission(1);
        shopInfoService.updateById(shopInfo);

        log.info("[申请疫苗资质成功] shopId={}", shopInfo.getId());
    }

    /**
     * 转换为VO
     */
    private QualificationVO convertToVO(ShopQualification qualification) {
        QualificationVO vo = new QualificationVO();
        BeanUtil.copyProperties(qualification, vo);

        // 解析JSON字段
        if (qualification.getQualificationImages() != null) {
            vo.setQualificationImages(JSONUtil.toList(qualification.getQualificationImages(), String.class));
        }

        // 设置文本字段
        vo.setQualificationTypeText(getQualificationTypeText(qualification.getQualificationType()));
        vo.setAuditStatusText(getAuditStatusText(qualification.getAuditStatus()));

        return vo;
    }

    /**
     * 获取资质类型文本
     */
    private String getQualificationTypeText(Integer qualificationType) {
        if (qualificationType == null) {
            return "未知";
        }
        return switch (qualificationType) {
            case 1 -> "营业执照";
            case 2 -> "动物诊疗许可证";
            case 3 -> "其他";
            default -> "未知";
        };
    }

    /**
     * 获取审核状态文本
     */
    private String getAuditStatusText(Integer auditStatus) {
        if (auditStatus == null) {
            return "未知";
        }
        return switch (auditStatus) {
            case 0 -> "待审核";
            case 1 -> "审核通过";
            case 2 -> "审核驳回";
            default -> "未知";
        };
    }
}
